import * as pdfjsLib from 'pdfjs-dist/es5/build/pdf';
import * as pdfjsViewer from 'pdfjs-dist/es5/web/pdf_viewer';

const WORKER_SRC = `https://cdn.jsdelivr.net/npm/pdfjs-dist@${pdfjsLib.version}/es5/build/pdf.worker.js`;

class PdfLib {
  canvas;
  viewer;
  options;

  constructor(container, options) {
    const pdfContainer = typeof container === 'string' ? document.querySelector(container) : container;
    if (pdfContainer instanceof HTMLCanvasElement) {
      this.canvas = pdfContainer;
    } else {
      this.viewer = pdfContainer;
    }
    this.options = options;
    pdfjsLib.GlobalWorkerOptions.workerSrc = WORKER_SRC;
  }

  renderViewer(num): void {
    const eventBus = new pdfjsViewer.EventBus();
    this.loadPdf(this.options.docPath).then(doc => {
      return doc.getPage(num).then((pdfPage) => {
        const pdfPageView = new pdfjsViewer.PDFPageView({
          container: this.viewer,
          id: num,
          scale: 1.0,
          defaultViewport: pdfPage.getViewport({ scale: 1.0 }),
          eventBus,
          textLayerFactory: new pdfjsViewer.DefaultTextLayerFactory(),
          annotationLayerFactory: new pdfjsViewer.DefaultAnnotationLayerFactory(),
        });
        pdfPageView.setPdfPage(pdfPage);
        return pdfPageView.draw();
      });
    });
  }

  renderPage(num): void {
    this.loadPdf(this.options.docPath).then(doc => {
      doc.getPage(num).then(page => {
        console.log('page:', page);

        const viewport = page.getViewport({ scale: 1.0 });
        console.log('viewport:', viewport);

        const canvas: any = this.canvas;
        canvas.width = viewport.width;
        canvas.height = viewport.height;
        const ctx = canvas.getContext('2d');

        page.render({
          canvasContext: ctx,
          viewport,
        }).promise.then(() => {
          console.log('render then~~');
        });
      });
    });
  }

  loadPdf(path): any {
    const loadingTask = pdfjsLib.getDocument(path);
    return loadingTask.promise
      .then((pdfDocument) => {
        console.log('pdfDocument:', pdfDocument);
        return pdfDocument;
      })
      .catch((reason) => {
        console.error('Error: ' + reason);
      });
  }
}

export default PdfLib;
